using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using FireStarter.Base;
using FireStarter.Base.BusinessObjectMerger;
using Firestarter.DB.Schema.BO;
using Firestarter.DB.Schema.UI;
using Firestarter.DB_DomainModel.Logic;
using FireStarterModeller.BO;
using FireStarterModeller.Logic;
using FireStarterModeller.Logic.ClassDefExport;
using FireStarterModeller.Logic.FsStartLoading;
using FireStarterModeller.Logic.Wizards;
using Habanero.Base;
using Habanero.Base.Exceptions;
using Habanero.BO;
using Habanero.BO.ClassDefinition;
using Habanero.BO.Loaders;
using Habanero.Faces.Base;
using Habanero.Faces.Win;
using FireStarterModeller.UI;
using Microsoft.Practices.Unity;
using DialogResult = Habanero.Faces.Base.DialogResult;
using DockStyle=Habanero.Faces.Base.DockStyle;
using FormStartPosition = Habanero.Faces.Base.FormStartPosition;
using FormWindowState = Habanero.Faces.Base.FormWindowState;
using MessageBoxButtons = Habanero.Faces.Base.MessageBoxButtons;
using MessageBoxIcon = Habanero.Faces.Base.MessageBoxIcon;

namespace FireStarterModeller
{
    public class ProgramForm : FormWin
    {
        private readonly IFireStarterFormsController _fireStarterFormsController;
        private readonly IControlFactory _controlFactory;
        //private IMainMenuHabanero _mainMenuHabanero;
        private DMSolution _dmSolution;
        private IFormHabanero _mainControlForm;
        private DMClassAllDetailsControl _mainControl;
        private ToolStrip _toolStrip;
        private readonly IPanel _startupPanel;
        private static Form _startupSolutionForm;
        private RecentProjects _recentProjects;
        private HabaneroMenu _recentMenu;
       

        public ProgramForm(IFireStarterFormsController fireStarterFormsController)
        {
            fireStarterFormsController.MainProgramForm = this;
            _fireStarterFormsController = fireStarterFormsController;
            _controlFactory = _fireStarterFormsController.ControlFactory;

            SetBounds(0, 0, 1024 - 100, 768);
//            SetBounds(0, 0, 635, 580);
            StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
//            WindowState = FormWindowState.Maximized;
            IsMdiContainer = true;
            _startupPanel = CreateNewOpenControl();
            SetupMainMenu();
            SetupToolstrip();
            SetupMainControlForm();
            UpdateState();
            //if (Environment.UserDomainName != "CHILLI")
            //{
            //    this.WindowState = FormWindowState.Maximized;
            //}
            LoadApplication();
        }

        /// <summary>
        /// Loads the program depending on whether this is loaded from a saved .fstart file or a new Solution.
        /// </summary>
        private void LoadApplication()
        {
            if (Program.CommandArgs.Length == 0)
            {
                ShowStartupForm();
            }
            else
            {
                string projectFileName = Program.CommandArgs[0];
                OpenProject(projectFileName);
            }
        }

        /// <summary>
        /// Gets and Sets the Inversion of Control Container.
        /// </summary>
        [Dependency]
        public IUnityContainer IOCContainer { private get; set; }
        private DMSolution Solution
        {
            get { return _dmSolution; }
            set
            {
                if (_dmSolution != null)
                {
                    _dmSolution.Props["SolutionName"].Updated -= SolutionName_Updated;
                }
                _dmSolution = value;
                UpdatePropertyTypesLookupList();
                if (_dmSolution != null)
                {
                    _dmSolution.Props["SolutionName"].Updated += SolutionName_Updated;
                    _dmSolution.Deleted += DMSolution_OnDeleted;
                    ShowMainControlForm();
                    SetupMainMenu();
                }
                else
                {
                    HideMainControlForm();
                }
                UpdateState();
                _mainControl.Solution = _dmSolution;
//                new SolutionRenamer(_dmSolution).RenameAllClassesToStandardNames();
            }
        }

        private void UpdateState()
        {
            UpdateFormTitle();
            _toolStrip.Enabled = _dmSolution != null;
        }

        private void SetupMainControlForm()
        {
            _mainControlForm = _controlFactory.CreateForm();

            FormWin formWin = (FormWin)_mainControlForm;
            formWin.ControlBox = false;
            formWin.MinimizeBox = false;
            formWin.MaximizeBox = false;
            _mainControl = new DMClassAllDetailsControl(_controlFactory, _fireStarterFormsController);
            BorderLayoutManager layoutManager = _controlFactory.CreateBorderLayoutManager(_mainControlForm);
            layoutManager.AddControl(_mainControl, BorderLayoutManager.Position.Centre);
            _mainControl.SetForm(_mainControlForm);
            formWin.Icon = FMResources.FirestarterICON;
            this.Icon = FMResources.FirestarterICON;
        }

        private void ShowMainControlForm()
        {
            //if (_mainControlMenuItem == null)
            //{
            //    const string devMessage = "You cannot open the main form since the MainControlMenu has not yet been set up";
            //    throw new HabaneroDeveloperException(devMessage, devMessage);
            //}
            //_mainControlMenuItem.PerformClick();
            _mainControlForm.MdiParent = this;
            _mainControlForm.Show();
            _mainControlForm.WindowState = FormWindowState.Maximized;
            _mainControlForm.Refresh();
            this.Refresh();
        }

        private void HideMainControlForm()
        {
            _mainControlForm.Hide();
            _mainControlForm.MdiParent = null;
            _mainControlForm.Refresh();
            this.Refresh();
        }

        private void UpdatePropertyTypesLookupList()
        {
            if (_dmSolution != null)
            {
                BusinessObjectLookupList businessObjectLookupList = new BusinessObjectLookupList
                    ("FireStarterModeller.BO", "DMPropertyType", "SolutionID=" + _dmSolution.SolutionID, "PropertyTypeName");
                ClassDef classDef = ClassDef.Get<DMProperty>();
                classDef.PropDefcol["PropertyTypeID"].LookupList = businessObjectLookupList;
            }
        }

        private void DMSolution_OnDeleted(object sender, BOEventArgs e)
        {
            try
            {
                _mainControl.Solution = null;
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
        }

        private void SolutionName_Updated(object sender, BOPropEventArgs e)
        {
            try
            {
                UpdateFormTitle();
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
        }

        private void UpdateFormTitle()
        {
            string solutionName = _dmSolution != null ? _dmSolution.SolutionName : "(No Solution)";
            this.Text = string.Format("{0} - {1} {2}", solutionName, GlobalRegistry.ApplicationName, GlobalRegistry.ApplicationVersion);
        }

        //protected override void OnShown(EventArgs e)
        //{
        //    base.OnShown(e);
        //    ShowMainControlForm();
        //}

        protected override void OnClosing(CancelEventArgs e)
        {
            if (!PromptSaveSolution()) e.Cancel = true;
            base.OnClosing(e);
        }

        private void SetupMainMenu()
        {
            IControlFactory controlFactory = GlobalUIRegistry.ControlFactory;
            HabaneroMenu mainMenu = new HabaneroMenu("Main", this, controlFactory);
            HabaneroMenu fileMenu = mainMenu.AddSubMenu("File");
            SetupFileMenu(controlFactory, fileMenu);

            HabaneroMenu viewMenu = mainMenu.AddSubMenu("View");
            SetupViewMenu(viewMenu);

            HabaneroMenu helpMenu = mainMenu.AddSubMenu("Help");
            SetupHelpMenu(helpMenu);

            #region Historical Menu Items
            //fileMenu.AddMenuItem("Entities").FormControlCreator = (() =>
            //                                                      new DMSolutionControl
            //                                                          (controlFactory)
            //                                                          {Solution = _dmSolution});

            //fileMenu.AddMenuItem("DMProject Modules").FormControlCreator =
            //        () => new TestFormControl<DMAssembly>(controlFactory,
            //                                              new ProjectAssemblyInfoControl(controlFactory),
            //                                              new BusinessObjectCollection<DMAssembly>());

            //fileMenu.AddMenuItem("UIGridColumnInfo").FormControlCreator = 
            //        (() => new UIColumnInfoControl (controlFactory));

            //fileMenu.AddMenuItem("Test new UI").CustomHandler += (sender, e) => TestNewUI();

            //fileMenu.AddMenuItem("New Main Control").FormControlCreator =
            //        (() => new DMClassAllDetailsControl { Solution = _dmSolution });


            //fileMenu.AddMenuItem("Test Collapsible").FormControlCreator =
            //         (() => new TestCollapsible());
            #endregion Historical Menu Items

            IMainMenuHabanero mainMenuHabanero = new MenuBuilderWin(controlFactory).BuildMainMenu(mainMenu);
            mainMenuHabanero.DockInForm(this);
        }

        private void SetupFileMenu(IControlFactory controlFactory, HabaneroMenu fileMenu)
        {
            fileMenu.AddMenuItem("New").CustomHandler += ((sender, e) => CreateNewProject());
            fileMenu.AddMenuItem("Open").CustomHandler += ((sender, e) => OpenProject());
            fileMenu.AddMenuItem("Save").CustomHandler += ((sender, e) => SaveProject());
            fileMenu.AddMenuItem("Save As").CustomHandler += ((sender, e) => SaveProjectAs());
            //fileMenu.AddMenuItem("Main").CustomHandler = (sender, e) => ShowMainControlForm();
            //fileMenu.AddMenuItem("Hide Main").CustomHandler = (sender, e) => HideMainControlForm();
            fileMenu.AddMenuItem("Generate &Code ...").CustomHandler += GenerateCode_ClickHandler;
            fileMenu.AddMenuItem("Import From Database ...").CustomHandler += ((sender, e) => ImportFromDatabase());
            fileMenu.AddMenuItem("Create Solution from ClassDefs Xml...").CustomHandler += ((sender, e) => CreateFromClassDefs());
            fileMenu.AddMenuItem("Export Solution to ClassDefs Xml...").CustomHandler += ((sender, e) => ExportFromClassDefs(controlFactory));
            if (Solution != null)
            {
                fileMenu.AddMenuItem("Update Solution from ClassDefs Xml...").CustomHandler += ((sender, e) => ImportClassDefsIntoSolution());
                fileMenu.AddMenuItem("Close Solution").CustomHandler += ((sender, e) => CloseCurrentSolution());
            }
            _recentMenu = fileMenu.AddSubMenu("Recent Files");
            LoadProjectList();
            fileMenu.AddMenuItem("E&xit").CustomHandler += delegate { this.Close(); };
        }

        private void CloseCurrentSolution()
        {
            Solution.Save();
            FMDataStore.Reset();
            this.Solution = null;
            CloseAllForms();
        }

        private void SetupViewMenu(HabaneroMenu viewMenu)
        {
            viewMenu.AddMenuItem("Error List").CustomHandler += Validate_ClickHandler;
        }

        private void SetupHelpMenu(HabaneroMenu helpMenu)
        {
            helpMenu.AddMenuItem("Tutorial (Online)").CustomHandler += TutorialMenuItem_Click;
            helpMenu.AddMenuItem("About...").CustomHandler += AboutMenuItem_Click;
        }
        
        private void AboutMenuItem_Click(object sender, EventArgs e)
        {
            About form = new About();
            form.Show(this);
        }

        private void ExportFromClassDefs(IControlFactory controlFactory)
        {
            if (_dmSolution != null)
            {
                SolutionValidator solutionValidator = new SolutionValidator(_dmSolution, _fireStarterFormsController);
                if (!solutionValidator.CheckSolutionIsValid()) return;
                
                string fileName;
                string initialDirectory = "";
                if (!String.IsNullOrEmpty(_dmSolution.BOProjectName) && !String.IsNullOrEmpty(_dmSolution.SolutionDirectory))
                {
                    initialDirectory = _dmSolution.SolutionDirectory +@"\source\"+ _dmSolution.BOProjectName;
                    if (!Directory.Exists(initialDirectory)) return;
                }
                if (DialogUtilities.GetSaveFileName(this, out fileName, "xml", "ClassDef XML File", "ClassDefs", "Export Class Def", true, initialDirectory))
                {
                    string xml = XmlWriterClassDMs.CreateClassDMXml(Solution);
                    XmlUtilities.SaveToFile(fileName, xml);
                    //File.WriteAllText(fileName, xml);
                    controlFactory.ShowMessageBox("Solution Exported to ClassDefs Xml successfully.");
                }
            }
        }

        private void CreateFromClassDefs()
        {
            string fileName;
            if (!DialogUtilities.GetOpenFileName(this, out fileName, "xml", ""))
                return;
            //ResetDataAccessor();
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                ShowProgressBar();
                this.Refresh();
                FMDataStore.Reset();
                UpdateProgressBar(25);
                var classDefToSolutionImporter = new ClassDefToNewSolutionImporter(IOCContainer, fileName);
                classDefToSolutionImporter.ImportProgressChanged += (sender, e) => UpdateProgressBar(e.ProgressPercentage);
                DMSolution dmSolution = classDefToSolutionImporter.Import();
                Solution = dmSolution;
            }
            finally
            {
                HideProgressBar();
                Cursor.Current = Cursors.Default;
            }

        }
        

        private void ImportClassDefsIntoSolution()
        {
            string fileName;
            if (!DialogUtilities.GetOpenFileName(this, out fileName, "xml", ""))
                return;
            //SetupNewDataAccessor();
            //ImportClassDefsAndMergeWithExistingSolution(fileName);
            try
            {

                Cursor.Current = Cursors.WaitCursor;
                ShowProgressBar();
                this.Refresh();
                UpdateProgressBar(25);
                ClassDefToExistingSolutionImporter classDefToExistingSolutionImporter = new ClassDefToExistingSolutionImporter(IOCContainer, fileName, Solution);
                classDefToExistingSolutionImporter.ImportProgressChanged +=  (sender, e) => UpdateProgressBar(e.ProgressPercentage);
                Solution = classDefToExistingSolutionImporter.Import();
            }
            finally
            {
               HideProgressBar();
               Cursor.Current = Cursors.Default;
            }

        }

        //private void ImportClassDefsAndMergeWithExistingSolution(string fileName)
        //{
        //    FixUITabNames(_dmSolution);
        //    //FixAssembly(_dmSolution);
        //    _dmSolution.Save();
        //    //
        //    //TODO brett 03 May 2010: This is identical to the CreateFromClassDefs refactor to common code.
        //    // SetupNewDataAccessor();

        //    DMSolution tempSolution = GetSolutionCreator().CreateSolution();

        //    tempSolution.Assemblies.ForEach(assembly => assembly.MarkForDelete()); 
        //    ((IMergableBo)tempSolution).PendingChangeType = ChangeType.None;
        //    try
        //    {
        //        XmlClassDefsLoader loader = new XmlClassDefsLoader("", new DtdLoader(),
        //                                                           new FMDefClassFactory(tempSolution));
        //        loader.LoadClassDefs(File.ReadAllText(fileName));
        //        if (tempSolution.DefaultAssembly == null) tempSolution.DefaultAssembly = tempSolution.Assemblies.FirstOrDefault();
        //        /*                DMSolutionPostLoadProcessor processor = new DMSolutionPostLoadProcessor(IOCContainer);
        //                        processor.ProcessSolution(dmSolution);*/
        //    }
        //    catch (Exception ex)
        //    {
        //        GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
        //    }
        //    FixUITabNames(tempSolution);

        //    BORegistry.DataAccessor = new NonValidatingDataAccessorInMemory(_dataStoreInMemory);
             
        //    IMergeBO<DMSolution> merger = new MergeBO<DMSolution>();
        //    //FixAssembly(_dmSolution);
        //    _dmSolution = merger.MergeBOFrom(tempSolution, _dmSolution);

        //    merger.UpdatePendingChangeType(_dmSolution);
        //    var solutionTraverser = new SolutionTraverser();
        //    solutionTraverser.MarkForDeleteAllChangeTypeDelete(_dmSolution);
        //    DMSolutionPostLoadProcessor processor2 = new DMSolutionPostLoadProcessor(IOCContainer);
        //    processor2.ProcessSolution(_dmSolution);
        //    Solution = _dmSolution;
        //    //Ensure that the Temp solution is removed from the _dataStoreInMemory
        //    new DMSolutionDeleter(tempSolution).Delete();
        //}

        //private static void FixUITabNames(IDMSolution dmSolution)
        //{
        //    if (dmSolution == null) throw new ArgumentNullException("dmSolution");
        //    dmSolution.AllClasses.ForEach(
        //        @class => @class.UIViews.ForEach(
        //            view =>
        //                {
        //                    UIFormInfo info = view.UIFormInfo;
        //                    if (info == null) return;
        //                    info.UITabs.ForEach(
        //                        tab => { if (String.IsNullOrEmpty(tab.Name)) tab.Name = "default"; });
        //                }));
        //}


        private void ImportFromDatabase()
        {
            var tempSolution = this.Solution;
            //This line of code seems strange but is required to prevent the UI from 
            // updating during reverse engineering.
            // The solution cannot be set to null since this does not clear all the grid to BO bindings.
            //This also fixes Redmine BUG_ #830.
            this.Solution = new DMSolution();

            if (tempSolution == null)
            {
                //ResetDataAccessor();
                FMDataStore.Reset();
                tempSolution = GetSolutionCreator().CreateSolution();
            }
            if (tempSolution != null)
            {
                tempSolution.Save();
                try
                {
                    var dbReverseEngineeringController = new DBToDMReverseEngineeringController(tempSolution);
                    var reverseEngineering = dbReverseEngineeringController.CreateReverseEngineeringForSolution(new ReverseEngineeringSettings(), new DatabaseConnectionInfo());
                    if (reverseEngineering==null) throw new HabaneroDeveloperException("ReverseEngineering for the current solution has not been setup correctly");
                    var dbToDMImporterFactory = dbReverseEngineeringController.CreateDBToDMImporterFactory();
                    var dbChangesImporter = dbToDMImporterFactory.CreateDBChangesImporter();

                    DbSchemaReverseEngineeringWizardControl.ShowDBReverseEngineeringWizard(_fireStarterFormsController, reverseEngineering, dbChangesImporter);
                    
                    this.Solution = tempSolution;


                    SolutionValidator validator = new SolutionValidator(this.Solution,
                                                                        this._fireStarterFormsController);
                    if (validator.CheckSolutionIsValid())
                    {
                        GlobalUIRegistry.ControlFactory.ShowMessageBox("The solution '" + tempSolution.SolutionName +
                                                                       "' is valid");
                        if (this.Solution.ReverseEngineering != null)
                        {
                            ITransactionCommitter committer = BORegistry.DataAccessor.CreateTransactionCommitter();
                            committer.AddBusinessObject(this.Solution.ReverseEngineering.StoredDatabase);
                            committer.AddBusinessObject(this.Solution);
                            committer.CommitTransaction();
                        }
                    }
                }
                catch (Exception ex)
                {
                    GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
                }
            }
        }



        private static SolutionCreator GetSolutionCreator()
        {
            return new SolutionCreator();
        }

        private void ShowStartupForm()
        {
            try
            {
               //StartupSolutionControl startupSolutionControl = new StartupSolutionControl();
                IControlFactory controlFactory = GlobalUIRegistry.ControlFactory;
                _startupSolutionForm = (Form) controlFactory.CreateForm();
                _startupSolutionForm.BackColor = Color.White;
                _startupSolutionForm.FormBorderStyle = (System.Windows.Forms.FormBorderStyle) Habanero.Faces.Base.FormBorderStyle.None;
                _startupSolutionForm.BackgroundImage = ResourceFireStarter.background;
                _startupSolutionForm.BackgroundImageLayout = ImageLayout.None;
//                _startupSolutionForm.Width = 610;
                _startupSolutionForm.Height = 1000;
                _startupSolutionForm.Controls.Add((Control) _startupPanel);
                //startupSolutionControl.SolutionSaved += StartupSolutionControl_OnSolutionSaved;
                _startupSolutionForm.MdiParent = this;
//                _startupSolutionForm.Dock = (System.Windows.Forms.DockStyle) Habanero.Faces.Base.DockStyle.Fill;
                _startupSolutionForm.Dock = (System.Windows.Forms.DockStyle) DockStyle.Fill;
                _startupSolutionForm.Show();
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
        }

//        private void StartupSolutionControl_OnSolutionSaved(object sender, BOEventArgs<DMSolution> e)
//        {
//            try
//            {
//                DMSolution dmSolution = e.BusinessObject;
//                _startupSolutionForm.Close();
//                if (dmSolution == null) return;
//                Solution = dmSolution;
//                UpdateRecentSolution();
////                if (_mainControl == null)
////                {
////                   _mainControlMenuItem.PerformClick();
////                }
////                else
////                {
////                    _mainControl.Solution = Solution;
////                }
//            }
//            catch (Exception ex)
//            {
//                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
//            }
//        }

        private void TutorialMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.habanerolabs.com/Tutorials/tabid/116/Default.aspx");
        }

        private void GenerateCode_ClickHandler(object sender, EventArgs e)
        {
            try
            {
                if (_dmSolution != null)
                {
                    CodeGenerationForm codeGenerationForm = new CodeGenerationForm(_dmSolution);
                    codeGenerationForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
                    codeGenerationForm.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error in Code Generation");
            }
        }

        #region New Solution

        private void CreateNewProject()
        {
            try
            {
                bool promptSaveSolution = PromptSaveSolution();
                if (!promptSaveSolution) return;
                string fileName;
                bool createNew = DialogUtilities.GetSaveFileName(this, out fileName,
                    DefaultFirestarterFileExtension, "FireStarter Project File", "NewProject", "New Project", true, false);
                if (!createNew) return;
                //ResetDataAccessor();
                FMDataStore.Reset();
                SolutionCreator solutionCreator = new SolutionCreator();
                DMSolution dmSolution = solutionCreator.CreateSolution(fileName);
                UpdateSolutionLocation(fileName, dmSolution);
                dmSolution.Save();
                CloseAllForms();
                Solution = dmSolution;
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }

        }

        private static void UpdateSolutionLocation(string fileName, DMSolution dmSolution)
        {
            dmSolution.SolutionDirectory = Path.GetDirectoryName(fileName);
            dmSolution.ProjectFileName = fileName;
        }

        #endregion New Solution

        #region Open Solution

        private void OpenProject()
        {
            try
            {
                string fileName;
                if (!DialogUtilities.GetOpenFileName(this, out fileName, DefaultFirestarterFileExtension, "FireStarter DMProject File"))
                    return;
               
                OpenProject(fileName);
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
           
        }

        private static string DefaultFirestarterFileExtension
        {
            get { return "fstart"; }
        }

        private void OpenProject(string fileName)
        {
            try
            {
                bool promptSaveSolution = PromptSaveSolution();
                if (!promptSaveSolution) return;

                DMClass.Loading = true;
                LoadDataStoreFromFile(fileName);

                DMSolution dmSolution = Broker.GetBusinessObjectCollection<DMSolution>("").FirstOrDefault();
                if (dmSolution == null)
                {
                    throw new HabaneroApplicationException("There is no solution loaded from the selected file '" + fileName + "'");
                }
                UpdateSolutionLocation(fileName, dmSolution);
                CloseAllForms();
                Solution = dmSolution;
                UpdateRecentSolution();
                AddToRecentProjects(fileName);
                SolutionLoader.LoadAllSolutionBusinessObjects(Solution);

                DomainModelVersioner.UpdateSolution(Solution);
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "The Selected File '" + fileName +"' does not appear to be a valid firestarter project file. If this is from an old version of Firestarter then please recreate the Firestarter project by importing the Relevant ClassDef.XML", "Error Opening Solution");
            }
            finally
            {
                DMClass.Loading = false;
            }
            
        }

        #endregion Open Solution

        #region Save Solution

        private void SaveProject()
        {
            if (_dmSolution != null)
            {
                string fileName = _dmSolution.ProjectFileName;
                if (String.IsNullOrEmpty(fileName))
                {
                    SaveProjectAs();
                    return;
                }
                SaveProject(fileName);
            }
        }

        private void SaveProjectAs()
        {
            if (_dmSolution != null)
            {
                string fileName;

                if (!DialogUtilities.GetSaveFileName(this, out fileName,
                                                     DefaultFirestarterFileExtension, "FireStarter Project File", _dmSolution.SolutionName)) return;
                SaveProject(fileName);
                AddToRecentProjects(fileName);
            }
        }

        private void SaveProject(string fileName)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (_dmSolution != null)
                {
                    _dmSolution.Save();
                }
                new FsStartLoader().SaveDataStoreToFile(FMDataStore.FMDataStoreInMemory, fileName);
                //new FsStartLoader().SaveDataStoreToFile(_dataStoreInMemory, fileName);
                AddToRecentProjects(fileName);
                Cursor.Current = Cursors.Default;
                _controlFactory.ShowMessageBox("FireStarter Project Saved", "Saved", MessageBoxButtons.OK,
                                               MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
        }

        #endregion Save Solution

        private void UpdateRecentSolution()
        {
//            if (_dmSolution == null) return;
//            BusinessObjectCollection<RecentSolution> collection =
//                BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObjectCollection<RecentSolution>("");
//            RecentSolution recentSolution;
//            if (collection.Count > 0)
//            {
//                recentSolution = collection[0];
//                DMSolution solution1 = recentSolution.Solution1;
//                DMSolution solution2 = recentSolution.Solution2;
//                DMSolution solution3 = recentSolution.Solution3;
//                if (_dmSolution == solution1 || _dmSolution == solution2 || _dmSolution == solution3) return;
//                recentSolution.Solution3 = solution2;
//                recentSolution.Solution2 = solution1;
//                recentSolution.Solution1 = _dmSolution;
//                recentSolution.Save();
//            }
//            else
//            {
//                recentSolution = new RecentSolution { Solution1 = _dmSolution };
//                recentSolution.Save();
//            }
        }

        private bool PromptSaveSolution()
        {
            try
            {
                if (_dmSolution != null && _dmSolution.Status.IsDirty)
                {
                    DialogResult dialogResult = _controlFactory.ShowMessageBox
                        ("Do you want to save your changes?", "Save Changes",
                        MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    switch (dialogResult)
                    {
                        case DialogResult.No:
                            _dmSolution.CancelEdits();
                            break;
                        case DialogResult.Yes:
                            SaveProject();
                            break;
                        case DialogResult.Cancel:
                            return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
                return false;
            }
        }

        private void CloseAllForms()
        {
            //foreach (Form form in this.MdiChildren)
            //{
            //    form.Close();
            //}
        }

        //private void ResetDataAccessor()
        //{
        //    //BORegistry.DataAccessor = new NonValidatingDataAccessorInMemory();
        //    _dataStoreInMemory = new DataStoreInMemory();
        //    //BORegistry.DataAccessor = new DataAccessorInMemory(_dataStoreInMemory);
        //    BORegistry.DataAccessor = new NonValidatingDataAccessorInMemory(_dataStoreInMemory);
        //    BusinessObjectManager.Instance.ClearLoadedObjects();            
        //}

        private void LoadProjectList()
        {
            List<string> projectsList = RecentProjects.ProjectsList;
            List<HabaneroMenu.Item> items = _recentMenu.MenuItems;
            items.Clear();
            foreach (string project in projectsList)
            {
                _recentMenu.AddMenuItem(project);
            }
            items = _recentMenu.MenuItems;
            foreach (HabaneroMenu.Item recentItem in items)
            {
                recentItem.CustomHandler += OpenRecentFile_Click;
            }
        }

        private void OpenRecentFile_Click(object sender, EventArgs e)
        {
            MenuItem menuItem = (MenuItem)sender;
            OpenProject(menuItem.Text);
        }

        private static void LoadDataStoreFromFile(string fileName)
        {
            FMDataStore.Reset();
            FMDataStore.FMDataStoreInMemory.AllObjects = new FsStartLoader().LoadDataStoreFromFile(fileName);
        }


        #region Toolstrip

        private void SetupToolstrip()
        {
            _toolStrip = new ToolStrip
                             {
                                 ImageScalingSize = new Size(40, 25),//new Size(36, 20), 
                                 GripStyle = ToolStripGripStyle.Hidden
                             };
            
            //AddToolStripButton(toolStrip, "Maintain Solutions", ResourceFireStarter.Solution, MaintainSolution_ClickHandler);
            //AddToolStripButton(_toolStrip, "Maintain Assemblies", ResourceFireStarter.Modules, MaintainModule_ClickHandler);
            AddToolStripButton(_toolStrip, "New Project", ResourceFireStarter.NewSolution, (sender, e) => CreateNewProject());
            AddToolStripButton(_toolStrip, "Open Project", ResourceFireStarter.Open, (sender, e) => OpenProject());
            AddToolStripButton(_toolStrip, "Edit Solution", ResourceFireStarter.Modules, EditSolution_ClickHandler);
            AddToolStripButton(_toolStrip, "New Class", ImageResources.GetImage("NewEntity.png"), NewClass_ClickHandler);
            AddToolStripButton(_toolStrip, "Save", ResourceFireStarter.Save, (sender, e) => SaveProject());
            AddToolStripButton(_toolStrip, "Import from Database",ResourceFireStarter.importFromDatabase, (sender, e) => ImportFromDatabase());
            AddToolStripButton(_toolStrip, "Create Solution from ClassDefs Xml", ResourceFireStarter.CreateSolutionFromClassDefs, (sender, e) => CreateFromClassDefs());
            AddToolStripButton(_toolStrip, "Export Solution to ClassDefs Xml", ResourceFireStarter.ExportToClassDefs, (sender, e) => ExportFromClassDefs(_controlFactory));
            AddToolStripButton(_toolStrip, "Validate", ResourceFireStarter.Validate, Validate_ClickHandler);
            AddToolStripButton(_toolStrip, "Generate Code", ResourceFireStarter.Publish, GenerateCode_ClickHandler);
            AddToolStripButton(_toolStrip, "Dump State", null, (sender, e) => DumpDataStore());
            AddToolStripProgressBar();
            //AddToolStripButton(_toolStrip, "Non file Save", ResourceFireStarter.Save, (sender, e) => _dmSolution.Save());
            this.Controls.Add(_toolStrip);
        }

        private void DumpDataStore()
        {
            MemoryDumpUtilities memoryDumpUtilities = new MemoryDumpUtilities();
            //string dump = memoryDumpUtilities.DumpInMemoryDataStore(_dataStoreInMemory);
            string dump = memoryDumpUtilities.DumpInMemoryDataStore(FMDataStore.FMDataStoreInMemory);
            string fileName;
            if (DialogUtilities.GetSaveFileName(out fileName, "dmp", "Memory Dump",
                                            "FSDump " + DateTime.Now.ToString("yyyyddMM HHmmss"), "Save Memory Dump"))
            {
                File.WriteAllText(fileName, dump);
            }
        }

        private static void AddToolStripButton(ToolStrip toolStrip, string toolTip, Image image, EventHandler eventHandler)
        {
            ToolStripButton button = new ToolStripButton("", image, eventHandler);
            button.ToolTipText = toolTip;
            toolStrip.Items.Add(button);
        }

        private void AddToolStripProgressBar()
        {
            ToolStripProgressBar progressBar = new ToolStripProgressBar("ProgressBar");
            progressBar.Minimum = 0;
            progressBar.Maximum = 100;
            progressBar.Height = 25;
            progressBar.Width = 150;
            _toolStrip.Items.Add(progressBar);
            HideProgressBar();
        }

        private void UpdateProgressBar(int progressPercentage)
        {
            var progressBar = (ToolStripProgressBar)_toolStrip.Items.Find("ProgressBar", true)[0];
            progressBar.Value = progressPercentage;
        }

        private void HideProgressBar()
        {
            var progressBar = (ToolStripProgressBar)_toolStrip.Items.Find("ProgressBar", true)[0];
            progressBar.Visible = false;
        }

        private void ShowProgressBar()
        {
            var progressBar = (ToolStripProgressBar)_toolStrip.Items.Find("ProgressBar", true)[0];
            progressBar.Visible = true;
        }


        //private void MaintainSolution_ClickHandler(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        DMSolutionGridControl solutionGridControl = new DMSolutionGridControl(_controlFactory);
        //        IFormHabanero solutionForm = _controlFactory.CreateForm();
        //        solutionForm.Width = 600;
        //        solutionForm.Height = 550;
        //        solutionForm.Controls.Add(solutionGridControl);
        //        solutionGridControl.Dock = DockStyle.Fill;
        //        solutionForm.ShowDialog();
        //    }
        //    catch (Exception ex)
        //    {
        //        GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
        //    }
        //}

        //private void MaintainModule_ClickHandler(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        DMAssembliesGridControl assembliesGridControl = new DMAssembliesGridControl(_controlFactory) { DMSolution = _dmSolution };
        //        IFormHabanero assemblyForm = _controlFactory.CreateForm();
        //        assemblyForm.Width = 600;
        //        assemblyForm.Height = 550;
        //        assemblyForm.Controls.Add(assembliesGridControl);
        //        assembliesGridControl.Dock = DockStyle.Fill;
        //        assemblyForm.ShowDialog();
        //    }
        //    catch (Exception ex)
        //    {
        //        GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
        //    }
        //}

        private void EditSolution_ClickHandler(object sender, EventArgs e)
        {
            try
            {
                if (_dmSolution != null)
                {
                    var initialSolutionName = _dmSolution.SolutionName;
                    IDefaultBOEditorForm defaultBoEditorForm = _controlFactory.CreateBOEditorForm(_dmSolution);
                    defaultBoEditorForm.Closing += delegate {};


                    defaultBoEditorForm.ShowDialog();
                    if (defaultBoEditorForm.DialogResult == DialogResult.OK)
                    {
                        DialogResult dialogResult = _controlFactory.ShowMessageBox
                       ("Do you want to save your changes?", "Save Changes",
                       MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                        switch (dialogResult)
                        {
                            case DialogResult.No:
                                _dmSolution.CancelEdits();
                                break;
                            case DialogResult.Yes:
                                RenameDefaultAssembly(initialSolutionName);
                                SaveProject();
                                break;
                            case DialogResult.Cancel:
                                return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
        }

        private void RenameDefaultAssembly(string initialSolutionName)
        {
            var solutionRenamer = new SolutionRenamer(_dmSolution);
            solutionRenamer.RenameSolution(_dmSolution.SolutionName);
            
        }

#pragma warning disable 168
        private void NewClass_ClickHandler(object sender, EventArgs e)
        {
            try
            {
                DMClass newDMClass = _dmSolution.DefaultAssembly.Classes.CreateBusinessObject();
                IDefaultBOEditorForm defaultBOEditorForm = GlobalUIRegistry.ControlFactory.CreateBOEditorForm(newDMClass, "default");
                IPanelInfo panelInfo = defaultBOEditorForm.PanelInfo;
                RelationshipComboBoxMapper controlMapper = (RelationshipComboBoxMapper)panelInfo.FieldInfos["Assembly"].ControlMapper;
                controlMapper.BusinessObjectCollection = _dmSolution.Assemblies;

                defaultBOEditorForm.Closed += delegate
                {
                    if (newDMClass.Status.IsNew)
                    {
                        //classes.Remove(newDMClass);
                        newDMClass.MarkForDelete();
                        newDMClass.Save();

                    }
                    else
                    {
                        newDMClass.CreateObjectIdWithDefaultProp();
                    }
                };
                defaultBOEditorForm.ShowDialog();
                //This is a Hack to force the Assemblies classes to load this somehow causes the treeview to work
                if (newDMClass != null)
                {
                    DMAssembly assembly = newDMClass.Assembly;
                    if (assembly != null)
                    {
                        BusinessObjectCollection<DMClass> classes1 = assembly.Classes;

                    }
                }
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
        }
#pragma warning restore 168
        private void Validate_ClickHandler(object sender, EventArgs e)
        {
            SolutionValidator solutionValidator = new SolutionValidator(_dmSolution, _fireStarterFormsController);
            if (solutionValidator.CheckSolutionIsValid())
            {
                GlobalUIRegistry.ControlFactory.ShowMessageBox("The solution '" + _dmSolution.SolutionName + "' is valid");
            }
        }

/*
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProgramForm));
            this.SuspendLayout();
            // 
            // ProgramForm
            // 
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "ProgramForm";
            this.ResumeLayout(false);
            
        }
*/


        //private void Publish_ClickHandler(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        Cursor.Current = Cursors.WaitCursor;
        //        if (_dmSolution == null) return;
        //        _dmSolution.Save();
        //        IList<IBOError> errors = _dmSolution.Validate();
        //        if (errors.Count > 0)
        //        {
        //            ShowErrorsForSolution(errors);
        //            return;
        //        }
        //        ClassDefExporter configurationExporter = new ClassDefExporter();
        //        try
        //        {
        //            configurationExporter.ExportSolution(_dmSolution);

        //            configurationExporter.UpdateBOStatus
        //                (_dmSolution, ConfigurationExporter.UpdateBOAndGeneratedPropToDirty);
        //            _dmSolution.Save();

        //            GlobalUIRegistry.ControlFactory.ShowMessageBox
        //                ("The solution '" + _dmSolution.SolutionName + "' has been published.", "Solution Published",
        //                 MessageBoxButtons.OK, MessageBoxIcon.Information);
        //        }
        //        catch (Exception ex)
        //        {
        //            Cursor.Current = Cursors.Default;
        //            GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error Publishing Solution");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Cursor.Current = Cursors.Default;
        //        GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
        //    }
        //    finally
        //    {
        //        Cursor.Current = Cursors.Default;
        //    }
        //}

        #endregion Toolstrip

        #region StartUpControl

        private IPanel CreateNewOpenControl()
        {
            Image image1 = FMResources.Load;
            LabelWin newImageLabel = new LabelWin
            {
                Size = new Size(image1.Width, image1.Height),
                Image = image1,
                Top = 100, 
                Left = 50
            };
            LinkLabel newLinkLabel = new LinkLabel
            {
                Width = 300,
                Text = @"Create New Solution",
                LinkColor = Color.Black,
                LinkBehavior = LinkBehavior.NeverUnderline,
                Font = new System.Drawing.Font("Arial", 12, FontStyle.Bold),
                Top = 100, 
                Left = newImageLabel.Left + newImageLabel.Width + 20
                
            };
            newLinkLabel.Click += (sender, e) => CreateNewProject(); 

            LabelWin dbImageLabel = new LabelWin
            {
                Size = new Size(image1.Width, image1.Height),
                Image = image1,
                Top = 145,
                Left = 50
            };
            LinkLabel dbLinkLabel = new LinkLabel
            {
                Width = 300,
                Text = @"Create Solution from Database",
                LinkColor = Color.Black,
                LinkBehavior = LinkBehavior.NeverUnderline,
                Font = new System.Drawing.Font("Arial", 12, FontStyle.Bold),
                Top = dbImageLabel.Top,
                Left = newImageLabel.Left + newImageLabel.Width + 20
            };
            dbLinkLabel.Click += (sender,e) => ImportFromDatabase();

            LabelWin classdefsImageLabel = new LabelWin
            {
                Size = new Size(image1.Width, image1.Height),
                Image = image1,
                Top = 190,
                Left = 50
            };
            LinkLabel classdefsLinkLabel = new LinkLabel
            {
                Width = 300,
                Text = @"Create Solution from ClassDefs",
                LinkColor = Color.Black,
                LinkBehavior = LinkBehavior.NeverUnderline,
                Font = new System.Drawing.Font("Arial", 12, FontStyle.Bold),
                Top = classdefsImageLabel.Top,
                Left = newImageLabel.Left + newImageLabel.Width + 20
            };
            classdefsLinkLabel.Click += (sender, e) =>  CreateFromClassDefs();

            LabelWin openImageLabel = new LabelWin
            {
                Size = new Size(image1.Width, image1.Height),
                Image = image1,
                Top = 235,
                Left = 50
            };
            LinkLabel openLinkLabel = new LinkLabel
            {
                Width = 300,
                Text = @"Open Existing Solution",
                LinkColor = Color.Black,
                LinkBehavior = LinkBehavior.NeverUnderline,
                Font = new System.Drawing.Font("Arial", 12, FontStyle.Bold),
                Top = openImageLabel.Top,
                Left = newImageLabel.Left + newImageLabel.Width + 20
            };
            openLinkLabel.Click += (sender, e) => OpenProject();

            IPanel recentSolutionPanel = CreateRecentSolutionPanel();
            recentSolutionPanel.BackColor = Color.Transparent;
            recentSolutionPanel.Left = 50;
            recentSolutionPanel.Top = openImageLabel.Top + 5;

            IPanel developersPanel = CreateDevelopersPanel();
            developersPanel.BackColor = Color.Transparent;
            developersPanel.Left = 410;
            developersPanel.Top = 120;

            IPanel panel3 = _controlFactory.CreatePanel();
            panel3.BackColor = Color.Transparent;
            panel3.Height = 800;
            panel3.Width = 900;
            panel3.Controls.Add(newImageLabel);
            ((Panel)panel3).Controls.Add(newLinkLabel);
            panel3.Controls.Add(dbImageLabel);
            ((Panel)panel3).Controls.Add(dbLinkLabel);
            panel3.Controls.Add(classdefsImageLabel);
            ((Panel)panel3).Controls.Add(classdefsLinkLabel);
            panel3.Controls.Add(openImageLabel);
            ((Panel)panel3).Controls.Add(openLinkLabel);
            panel3.Controls.Add(recentSolutionPanel);
            panel3.Controls.Add(developersPanel);
            return panel3;
        }

        private IPanel CreateDevelopersPanel()
        {
            IPanel panel = _controlFactory.CreatePanel();
            panel.Height = 800;
            panel.Width = 500;

            LabelWin labelWin = new LabelWin
                                {
                                    AutoSize = true,
                                    Location = new System.Drawing.Point(10, 10),
                                    Text = @"Contributing Developers:",
                                    Font = new System.Drawing.Font("Arial", 10F, FontStyle.Bold),
                                    ForeColor = Color.Silver
                                };

            LabelWin devList = new LabelWin()
            {
               AutoSize = true,
               Location = new System.Drawing.Point(10, 40),
               Text = "Brett Powell\r\nDeerasha Singh\r\nDonald Mafa\r\nDuncan Hodgson\r\nEric Savage\r\nHagashen " +
                "Naidu\r\nJessica Benson\r\nMark Whitfeld\r\nPeter Wiles\r\nSherwin Moodley\r\nSoriya Das\r\n" +
                "Wajeeda Nabee\r\nAndrew Russell\r\nCharles Mkhile\r\n",
               Font = new System.Drawing.Font("Arial", 9F, FontStyle.Bold),
               ForeColor = Color.Silver
            };

            LabelWin habaneroLabel = new LabelWin
            {
                AutoSize = true,
                Location = new System.Drawing.Point(10, 290),
                Text = @"Powered by",
                Font = new System.Drawing.Font("Arial", 9F, FontStyle.Bold),
                ForeColor = Color.Silver
            };
            
            Image habanero = ResourceFireStarter.HabaneroLogo;
            LabelWin imageLabel = new LabelWin
            {
                Size = new Size(30,25 ),
                Image = habanero,
                Location = new System.Drawing.Point(80, 285),
            };

            LabelWin habaneroLabel2 = new LabelWin
            {
                AutoSize = true,
                Location = new System.Drawing.Point(110, 290),
                Text = "Habanero",
                Font = new System.Drawing.Font("Arial", 9F, FontStyle.Bold),
                ForeColor = Color.Silver
            };

            LinkLabel siteLinkLabel = new LinkLabel
            {
                AutoSize = true,
                Location = new System.Drawing.Point(10, 320),
                Text = "http://www.habanerolabs.com/",
                LinkColor = Color.Silver,
                Font = new System.Drawing.Font("Arial", 9F, FontStyle.Bold)
            };
            siteLinkLabel.Click += (sender, e) => OpenWebSite();

            panel.Controls.Add(labelWin);
            panel.Controls.Add(devList);
            panel.Controls.Add(habaneroLabel);
            panel.Controls.Add(imageLabel);
            panel.Controls.Add(habaneroLabel2);
            ((Panel)panel).Controls.Add(siteLinkLabel);
            return panel;
        }

        private void OpenWebSite()
        {
            System.Diagnostics.Process.Start("http://www.habanerolabs.com/");
        }
        
        private IPanel CreateRecentSolutionPanel()
        {
            var panel = _controlFactory.CreatePanel();
            panel.Height = 500;
            panel.Width = 350;

            var projectsList = RecentProjects.ProjectsList;
            var labelWin = new LabelWin
            {
                Text = @"Recently Opened Solutions...",
                Top = 50,
                Width = 300,
                Font = new System.Drawing.Font("Arial", 10F, FontStyle.Bold),
                ForeColor = Color.DarkSalmon
            };
            panel.Controls.Add(labelWin);
            int topPos = 70;
            foreach (string project in projectsList)
            {
                string display = ShortenPathToLength(project, 40);
                LinkLabel label = CreateSolutionLabel(display, project, topPos);
                ((Panel)panel).Controls.Add(label);
                topPos += 20;
            }
            return panel;
        }

        private static string ShortenPathToLength(string path, int limit)
        {
            if (path.Length > limit)
            {
                string drive = path.Substring(0, 3);
                string filePath = path.Substring(3);
                int pos = filePath.Length - (limit - 3);
                filePath = filePath.Substring(pos);
                pos = filePath.IndexOf(@"\");
                if (pos >= 0)
                {
                    filePath = filePath.Substring(pos);
                }
                return drive + "..." + filePath;
            }
            return path;
        }

        private LinkLabel CreateSolutionLabel(string solutionName, string path, int topPosition)
        {
            var solutionLabel = new LinkLabel
            {
              Text = solutionName,
              Name = path,
              Top = topPosition,
              Width = 450,
              Left = 10,
              Font = new System.Drawing.Font("Arial", 9F, FontStyle.Bold),
              LinkBehavior = LinkBehavior.NeverUnderline,
              LinkColor = Color.Black
            };
            solutionLabel.Click += RecentItem_Click;
            return solutionLabel;
        }

        private void AddToRecentProjects(string classDefFileName)
        {
            RecentProjects.Add(classDefFileName);
            LoadProjectList();
        }

        private void RecentItem_Click(object sender, EventArgs e)
        {
            LinkLabel linkLabel = (LinkLabel)sender;
            OpenProject(linkLabel.Name);
        }

        private RecentProjects RecentProjects
        {
            get
            {
                if (_recentProjects == null)
                {
                    _recentProjects = new RecentProjects(Path.Combine(Application.StartupPath, "projects.xml"));
                }
                return _recentProjects;
            }
        }
        #endregion StartUpControl

    }

}
